<template>
  <zy-list-page-layout>
    <!-- 搜索区域 -->
    <template #search>
      <zy-query-form :query-params="queryParams" @query="handleQuery" @reset="resetQuery">
        <el-form-item label="权限名称" prop="authorityName">
          <el-input
            v-model="queryParams.authorityName"
            placeholder="请输入权限名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限编码" prop="authorityCode">
          <el-input
            v-model="queryParams.authorityCode"
            placeholder="请输入权限编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="权限分类" prop="authorityType">
          <el-select v-model="queryParams.authorityType" placeholder="请选择权限分类" clearable>
            <el-option
              v-for="item in authorityTypeOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>
      </zy-query-form>
    </template>

    <!-- 操作按钮区域 -->
    <template #action>
      <el-button type="primary" @click="handleAdd">新增权限</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <zy-pagination-table
        ref="paginationTableRef"
        :query="getAuthorityList"
        :query-params="queryParams"
        :auto-load="false"
        v-model:data="authorityList"
        v-model:total="total"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="authorityName" label="权限名称" min-width="120" />
        <el-table-column prop="authorityCode" label="权限编码" min-width="120" />
        <zy-table-dict-column
          prop="authorityType"
          label="权限分类"
          width="120"
          dict-type-code="AUTHORITY_TYPE"
        />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" />
        <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center" />
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </zy-pagination-table>
    </template>
  </zy-list-page-layout>

  <!-- 权限表单对话框 -->
  <Detail
    v-model:visible="dialogVisible"
    :authority-data="currentAuthority"
    :is-edit="isEdit"
    @success="handleSuccess"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  ElMessage,
  ElMessageBox,
  ElInput,
  ElButton,
  ElTableColumn,
  ElFormItem,
  ElSelect,
  ElOption
} from 'element-plus'
import {
  getAuthorityList,
  deleteAuthority,
  SysAuthority,
  AuthorityQueryParams
} from '@/api/system/authority'
// Business 组件已全局注册，无需导入
import { useDict } from '@/utils/dict'
import Detail from './Detail.vue'

// 响应式数据
const total = ref(0)
const authorityList = ref<SysAuthority[]>([])
const dialogVisible = ref(false)
const currentAuthority = ref<SysAuthority>()
const isEdit = ref(false)
const paginationTableRef = ref()

// 使用字典工具获取权限分类选项
const authorityTypeOptions = useDict('AUTHORITY_TYPE')

// 查询参数
const queryParams = reactive<AuthorityQueryParams>({
  pageNum: 1,
  pageSize: 10,
  authorityName: '',
  authorityCode: '',
  authorityType: ''
})

// 生命周期
onMounted(() => {
  nextTick(() => {
    if (paginationTableRef.value) {
      paginationTableRef.value.loadData()
    }
  })
})

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  if (paginationTableRef.value) {
    paginationTableRef.value.handleQuery()
  }
}

// 重置搜索
const resetQuery = () => {
  queryParams.authorityName = ''
  queryParams.authorityCode = ''
  queryParams.authorityType = ''
  queryParams.pageNum = 1
  if (paginationTableRef.value) {
    paginationTableRef.value.resetQuery()
  }
}

// 新增权限
const handleAdd = () => {
  isEdit.value = false
  currentAuthority.value = undefined
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row: SysAuthority) => {
  isEdit.value = true
  currentAuthority.value = { ...row }
  dialogVisible.value = true
}

// 删除权限
const handleDelete = async (row: SysAuthority) => {
  try {
    await ElMessageBox.confirm('确认删除该权限吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (!row.authorityId) {
      ElMessage.error('权限ID不能为空')
      return
    }

    const result: any = await deleteAuthority(row.authorityId)
    if (result === true || result.data === true) {
      ElMessage.success('删除成功')
      if (paginationTableRef.value) {
        paginationTableRef.value.loadData()
      }
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败')
    }
  }
}

// 表单提交成功回调
const handleSuccess = () => {
  if (paginationTableRef.value) {
    paginationTableRef.value.loadData()
  }
}
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
